<?php
function __autoload($class) {
	if (class_exists($class, false)) {
		return;
	}
	if (substr($class, 0, 10) == 'exception_') {
		eval("class $class extends Exception {}");
        return;
		//todo: should this be improved?
	}
	$path = str_replace('_', DIRECTORY_SEPARATOR, $class);
	$dirs = null;
	if ($path != $class) {
		$dirs = dirname($path);
		$file = basename($path) . '.php';
	} else {
		$file = $class . '.php';
	}
	if (preg_match('/[^a-z0-9\-_.]/i', $file)) {
		throw new Exception('Security check: Illegal character in filename',001);
    }
	$filespec = $file;
	if ($dirs === null) {
		$found = file_is_readable($filespec);
    } else {
		foreach ((array)$dirs as $dir) {
			$filespec = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR . $file;
			$found = file_is_readable($filespec);
			if ($found) {
				break;
    		}
    	}
    }
	if (!$found and substr($class,0,9) == 'callback_') {
    	eval("class $class implements callback_module {}");
    	return;
    }
	if (!$found) {
    	throw new Exception("File \"$filespec\" was not found.",002);
    }
	include($filespec);
	if (!class_exists($class, false)) {
		throw new Exception("File \"$file\" was loaded but class \"$class\" was not found within.",003);
	}
}
function file_is_readable($filename)
{
	$f = @fopen($filename, 'r', true);
	$readable = is_resource($f);
	if ($readable) {
		fclose($f);
	}
	return $readable;
}
?>